package com.sc.service;

import com.sc.dao.CartDao;
import com.sc.dao.CartItemDao;
import com.sc.dao.impl.CartDaoImpl;
import com.sc.dao.impl.CartItemDaoImpl;
import com.sc.entity.Cart;
import com.sc.entity.CartItem;
import com.sc.entity.Product;
import com.sc.entity.User;

public class CartService {
    private final static CartDao cartDao=new CartDaoImpl();
    private final static CartItemDao cartItemDao=new CartItemDaoImpl();
public void addProductInCart(User user, Product product,int count)throws Exception{
    if (count<1){
        throw new RuntimeException("数量不能小于1");
    }
    //找到购物车
    //select*from cart where user_id =?
    Cart cart=cartDao.findByUserId(user.getId());
    if (cart==null){
        cart=new Cart();
        cart.setUserId(user.getId());
        cartDao.add(cart);
        //处理购物车id问题
        cart=cartDao.findByUserId(user.getId());
    }
    //在数据库中去查询 有没有这类商品
    //select * from cart_item where cart_id =? and product_id=?
    CartItem cartItem= cartItemDao.finByCartIdAndProductId(cart.getId(),product.getId());
    if (cartItem != null) {
        cartItem.setProductNum(cartItem.getProductNum() + count);
        cartItem.setPrice(cartItem.getPrice());
        cartItemDao.update(cartItem);
    }else {
        cartItem=new CartItem();
        cartItem.setProductId(product.getId());
        cartItem.setCartId(cart.getId());
        cartItem.setProductNum(count);
        cartItem.setPrice(product.getPrice());
        cartItemDao.add(cartItem);
    }
}
public void removeProductInCart(User user,Product product)throws Exception{
    //找到购物车
    //select*from cart where user_id =?
    Cart cart=cartDao.findByUserId(user.getId());
    if (cart==null){
        throw new RuntimeException("购物车未找到");
    }
    //在数据库中去查询 有没有这类商品
    //select * from cart_item where cart_id =? and product_id=?
    CartItem cartItem=cartItemDao.finByCartIdAndProductId(cart.getId(),product.getId());
    if (cartItem != null){
        cartItemDao.deleteByCartIdAndProductId(cart.getId(),product.getId());
    }else {
        throw new RuntimeException("商品未找到");
    }
    System.out.println("操作成功");
}
}

